/**
 * 封装axios
 * @param 参数详解：https://github.com/axios/axios
 */
import axios from "axios";
import { logoutUser } from "../../utils/login";

// 默认配置
axios.defaults.method = "POST";
axios.defaults.withCredentials = true;

/**
 * 创建xhr实例
 * 路径前缀
 * 超时失败时间
 */
const service = axios.create({
  timeout: 50000,
  withCredentials: true,
});

/**
 * @desc 设置服务响应拦截器
 * 截取返回状态 统一定义成功失败
 */
service.interceptors.response.use(
  (response) => {
    const { data, config = {} } = response;
    const { responseType = null } = config;
    if (data && data.code !== 200 && responseType !== "blob") {
      const { message = "后台请求报错" } = data;
      console.log(message);
      return data;
    }
    return response;
  },
  (error) => {
    const { response } = error;
    // token失效，跳转到登录页面
    if (response.status === 401) {
      logoutUser();
      window.location.href = "/login";
      return false;
    }
    return Promise.reject(error);
  }
);

export const GET = (url: string, params: any = {}) => {
  const _config: any = {
    url,
    method: "get",
    // params,
    headers: {
      token: sessionStorage.getItem("TOKEN"),
    },
  };
  if (params.hasOwnProperty("data") && params.hasOwnProperty("json")) {
    _config.data = params.data;
  } else {
    _config.params = params;
  }
  return service(_config).then(
    (res) => {
      return res;
    },
    (rj) => {
      return Promise.reject(rj);
    }
  );
};

export const POST = (url: string, config: any = {}) => {
  const _url = url;
  let postData;
  const postConfig: any = {};
  const token = sessionStorage.getItem("TOKEN")
  if (Array.isArray(config)) {
    postData = config;
    postConfig.headers = {
      token,
    };
  } else {
    const { cancelToken, ContentType, _Pdata, responseType, ..._data } = config;
    postData = _Pdata || _data;
    if (ContentType && ContentType === "text/plain") {
      postData = _data.data;
    } else if (ContentType === "multipart/form-data") {
      postData = _data.data;
    }
    postConfig.headers = {
      token,
      ...(ContentType && { "Content-Type": ContentType }),
    };
    if (responseType) {
      postConfig.responseType = responseType;
    }
  }
  const _config = {};
  Object.assign(postConfig, {
    url: _url,
    data: postData,
    method: "POST",
    ..._config,
  });
  return service(postConfig)
    .then((res) => {
      return res;
    })
    .catch((err) => {
      return err.response;
    });
};
